/*
 * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/module-main/src/main/java/org/apache/http/message/BasicNameValuePair.java $
 * $Revision: 604625 $
 * $Date: 2007-12-16 06:11:11 -0800 (Sun, 16 Dec 2007) $
 *
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package com.koushikdutta.ion.sample;

import com.example.ohosasynclibrary.async.future.FutureCallback;
import com.example.ohosasynclibrary.async.future.SuccessCallback;
import com.example.ohosasynclibrary.async.http.AsyncHttpClient;
import com.example.ohosasynclibrary.async.http.AsyncHttpGet;
import com.example.ohosasynclibrary.async.http.AsyncHttpResponse;
import com.example.ohosasynclibrary.async.util.LogUtil;
import com.google.gson.JsonObject;
import com.koushikdutta.ion.ImageUtil;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.IonLog;
import com.koushikdutta.ion.future.ResponseFuture;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.PixelMap;
import org.apache.http.client.methods.HttpGet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 主 sample界面
 */
public class MainAbility extends Ability {
    private static final Logger logger = Logger.getLogger(MainAbility.class.getName());
    private final static String DOG_PICTURE = "https://httpbin.org/image/webp";
    private final static String VIEW_PICTURE = "https://httpbin.org/image/jpeg";
    private final static String GET_JSON = "https://httpbin.org";

    private final static String TEST_PIC1 = "http://inews.gtimg.com/newsapp_bt/0/12539530922/641";
    private final static String TEST_PIC2 = "http://inews.gtimg.com/newsapp_bt/0/12539530923/641";

    private Button loadImage1;
    private Button loadImage2;
    private Button loadImage3;
    private Button loadImage4;

    private Button loadImage5;
    private Button loadImage6;
    private Button loadImage7;
    private Button loadImage8;

    private Button mp4Download;
    private Button downloadCancel;

    private Image imageView1;
    private Image imageView2;
    private Image imageView3;
    private Image imageView4;
    private Text contentText;

    ResponseFuture<File> responseFuture1;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_main);

        imageView1 = (Image) findComponentById(ResourceTable.Id_imageView1);
        imageView2 = (Image) findComponentById(ResourceTable.Id_imageView2);
        imageView3 = (Image) findComponentById(ResourceTable.Id_imageView3);
        imageView4 = (Image) findComponentById(ResourceTable.Id_imageView4);
        loadImage1 = (Button) findComponentById(ResourceTable.Id_loadImage1);
        loadImage2 = (Button) findComponentById(ResourceTable.Id_loadImage2);
        loadImage3 = (Button) findComponentById(ResourceTable.Id_loadImage3);
        loadImage4 = (Button) findComponentById(ResourceTable.Id_loadImage4);
        loadImage5 = (Button) findComponentById(ResourceTable.Id_loadImage5);
        loadImage6 = (Button) findComponentById(ResourceTable.Id_loadImage6);
        loadImage7 = (Button) findComponentById(ResourceTable.Id_loadImage7);
        loadImage8 = (Button) findComponentById(ResourceTable.Id_loadImage8);
        mp4Download = (Button) findComponentById(ResourceTable.Id_mp4Download);
        downloadCancel = (Button) findComponentById(ResourceTable.Id_downloadCancel);
        contentText = (Text) findComponentById(ResourceTable.Id_contentText);

        ShapeElement background = new ShapeElement();
        background.setCornerRadius(25);
        background.setStroke(3, new RgbColor(255, 106, 106));

        loadImage1.setBackground(background);
        loadImage2.setBackground(background);
        loadImage3.setBackground(background);
        loadImage4.setBackground(background);
        loadImage5.setBackground(background);
        loadImage6.setBackground(background);
        loadImage7.setBackground(background);
        loadImage8.setBackground(background);
        mp4Download.setBackground(background);
        downloadCancel.setBackground(background);

        initClicked();
    }

    private void initClicked() {
        loadImage1.setClickedListener(component ->
                Ion.with(imageView1)
                        .centerCrop()
                        .load(TEST_PIC1));

        loadImage2.setClickedListener(component ->
                Ion.with(imageView2)
                        .centerInside()
                        .load(TEST_PIC2));

        loadImage3.setClickedListener(component -> {
            File f1 = ResourceUtils.getResourceRawFile(getContext(), "resources/rawfile/Androidify25.png", "Androidify25.png");
            Ion.with(this)
                    .load(f1)
                    .withBitmap()
                    .fitCenter()
                    .deepZoom()
                    .intoImageView(imageView3);
        });

        loadImage4.setClickedListener(component -> {
            File f2 = ResourceUtils.getResourceRawFile(getContext(), "resources/rawfile/telescope.jpg", "telescope.jpg");
            Ion.with(this)
                    .load(f2)
                    .withBitmap()
                    .centerCrop()
                    .deepZoom()
                    .intoImageView(imageView4);
        });

        loadImage5.setClickedListener(component -> {
            showDialogView();
        });

        loadImage6.setClickedListener(component ->
                Ion.with(this)
                        .load("https://api.androidhive.info/volley/person_object.json")
                        .asJsonObject()
                        .setCallback(new FutureCallback<JsonObject>() {
                            @Override
                            public void onCompleted(Exception e, JsonObject result) {
                                if (e != null) {
                                    return;
                                }
                                contentText.setText(result.toString());
                            }
                        }));

        mp4Download.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                downloadMp4();
            }
        });

        downloadCancel.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (responseFuture1 != null) {
                    responseFuture1.cancel();

                    if (responseFuture1.isCancelled()) {
                        new ToastDialog(getContext()).setText("download is canceled").show();
                    }

                }
            }
        });

    }

    private void downloadMp4() {
        responseFuture1 = Ion.with(getContext())
                .load("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
                .write(new File(getCacheDir(), System.currentTimeMillis() + "test.mp4"));
        responseFuture1.setCallback(new FutureCallback<File>() {
            @Override
            public void onCompleted(Exception e, File result) {
                if (e != null) {
                    return;
                }
                System.out.println("mp4 download successful path  -->" + result.getAbsolutePath());
                contentText.setText(result.getAbsolutePath());
            }
        });

    }

    private void showDialogView() {
        CommonDialog commonDialog = new CommonDialog(MainAbility.this);
        commonDialog.setContentText("下载中...");
        commonDialog.setSize(200, 200);
        commonDialog.setCornerRadius(10f);
        commonDialog.setAlignment(TextAlignment.CENTER);
        commonDialog.show();
        Ion.with(MainAbility.this)
                .load(TEST_PIC2)
                // and a ProgressDialog
                .progressDialog(commonDialog)
                // can also use a custom callback
                .progress((downloaded, total) -> {
                })
                .write(new File(getCacheDir(), System.currentTimeMillis() + "-file-test.jpeg"))
                .setCallback((e, file) -> {
                    // download done...
                    // do stuff with the File or error
                    if (e != null) {
                        e.printStackTrace();
                        return;
                    }
                    commonDialog.hide();

                    try {
                        contentText.setText(file.getCanonicalPath());
                    } catch (IOException ex) {
                        logger.log(Level.INFO, "IOException IN TEST");
                    }
                });
    }

    private File getResourceRawFile(String path, String fileName) {
        RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry(path);
        File file = null;
        Resource resource = null;
        FileOutputStream fos = null;
        if (rawFileEntry != null) {
            try {
                resource = rawFileEntry.openRawFile();
                file = new File(getCacheDir().getParent() + File.separator + fileName);
                fos = new FileOutputStream(file);
                byte[] b = new byte[1024];
                int length;
                while ((length = resource.read(b)) != -1) {
                    fos.write(b, 0, length);
                }
            } catch (IOException e) {
                logger.log(Level.INFO, e.getMessage());
            } finally {
                try {
                    if (resource != null) {
                        resource.close();
                    }
                } catch (IOException e) {
                    logger.log(Level.INFO, e.getMessage());
                }

                try {
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    logger.log(Level.INFO, e.getMessage());
                }
            }
        }
        return file;
    }
}
